package org.biubiu0002.baiblog.im.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import io.netty.channel.ChannelHandlerContext;
import org.biubiu0002.baiblog.im.dto.*;
import org.biubiu0002.baiblog.im.dto.message.Message;
import org.biubiu0002.baiblog.im.dto.message.MessageNotification;
import org.biubiu0002.baiblog.im.dto.message.MessageRequest;
import org.biubiu0002.baiblog.im.dto.message.MessageResponse;
import org.biubiu0002.baiblog.im.session.ServerSession;

/**
 * @Author: biubiu0002
 * @Date: 2022/10/25 13:54
 **/
public class Serializer {

    public static Message parseMessage(String json, ChannelHandlerContext ctx){
        Message message = JSON.parseObject(json, new TypeReference<Message>() {
        });
        ServerSession session = ServerSession.getSession(ctx);
        if(session==null){
            return message;
        }
        String sessionId = session.getSessionId();
        ImUserDto user = session.getUser();
        if(user==null){
            return message;
        }
        MessageRequest messageRequest = message.getMessageRequest();
        MessageResponse messageResponse = message.getMessageResponse();
        MessageNotification messageNotification = message.getMessageNotification();
        if(messageRequest !=null){
            messageRequest.setFrom(user.getUserUid());
            messageRequest.setFromNick(user.getNickname());
            message.setMessageRequest(messageRequest);
        }
        if(messageResponse!=null){
            message.setMessageResponse(messageResponse);
        }
        if(messageNotification!=null){
            message.setMessageNotification(messageNotification);
        }
        message.setSessionId(sessionId);
        return message;
    }
}
